<template>
	<uni-popup ref="classfiyPopup" background-color="#fff" type="center" border-radius="10px 10px 0 0"
		:is-mask-click="true">
		<view class="classfiyPopup">
			<uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-align="right" :label-width="100">
				<uni-forms-item label="名称" name="name" required>
					<uni-easyinput type="text" v-model="formData.name" placeholder="请输入分类名称" />
				</uni-forms-item>
				<uni-forms-item label="排序" name="sort">
					<uni-easyinput type="number" v-model.number="formData.sort" placeholder="请输入排序" />
				</uni-forms-item>
				<uni-forms-item label="缩略图" name="picurl">
					<select-one-img :width="100" ratio="9 / 16" v-model:formData="formData"></select-one-img>
				</uni-forms-item>
				<uni-forms-item label="是否推荐" name="select">
					<switch v-model="formData.select" color="#FFCC33" :checked="formData.select"
						style="transform:scale(0.8);transform-origin: left center;" @change="selectChange" />
				</uni-forms-item>
				<uni-forms-item label="是否启用" name="enable">
					<switch v-model="formData.enable" :checked="formData.enable" color="#FFCC33"
						style="transform:scale(0.8);transform-origin: left center;" @change="enableChange" />
				</uni-forms-item>
				<uni-forms-item>
					<view class="popueBtnGroup">
						<button type="primary" size="mini" @click="submit">{{typename}}</button>
						<button type="default" size="mini" @click="close">取消</button>
					</view>
				</uni-forms-item>
			</uni-forms>
		</view>
	</uni-popup>
</template>

<script setup>
	import { computed, nextTick, ref, watch } from "vue";
	import dayjs from "dayjs";
	import { cloudToHttps, compressAndConvertToWebp } from "@/utils/tools.js"
	import { showToast, uploadFileItem } from "../../../utils/common";

	const emits = defineEmits(["success"])
	const props = defineProps(["item", "type", "maxSort"]);
	const classifyCloudObj = uniCloud.importObject("admin-bizhi-classify", { customUI: true });
	const formRef = ref(null);
	const cropperRef = ref(null);
	const classfiyPopup = ref(null);
	const typename = computed(() => props.type == 'add' ? '新增' : '修改');
	const formData = ref({
		name: "",
		sort: 0,
		picurl: "",
		select: true,
		enable: false,
		tmpurl: ""
	});

	watch(() => props.item, (nv) => {
		formData.value = {
			...nv,
			tmpurl: nv.picurl
		}
	})

	const rules = ref({
		name: {
			rules: [{
					required: true,
					errorMessage: '请填写分类名称',
				},
				{
					minLength: 2,
					maxLength: 8,
					errorMessage: '{label}长度在 {minLength} 到 {maxLength} 个字符',
				}
			],
			label: "分类名称"
		}
	})

	//表单提交
	const submit = async () => {
		try {
			uni.showLoading({
				mask: true
			})
			await formRef.value.validate();
			if (formData.value.tmpurl && formData.value.tmpurl != formData.value.picurl) {
				let file = await uploadFileItem(formData.value.tmpurl);
				formData.value.picurl = cloudToHttps(file.fileID)
			}
			let { tmpurl, ...params } = formData.value

			let { errCode, errMsg } = props.type == 'add' ? await classifyCloudObj.add(params) :
				await classifyCloudObj.update(params);

			if (errCode != 0) {
				return showToast({
					title: errMsg
				});
			}
			showToast({
				title: typename.value + "成功"
			})
			close();
			formDataInit();
			emits("success", {
				msg: typename.value + "成功"
			})
		} catch (err) {
			console.log(err);
			showToast({
				title: err
			})
		} finally {
			uni.hideLoading();
		}
	}

	//上传图片到云端
	const uploadFile = async () => {
		let tmpurl = await compressAndConvertToWebp(formData.value.tmpurl);
		return await uniCloud.uploadFile({
			filePath: tmpurl,
			cloudPath: "wallpaper/" + dayjs().format("YYYYMMDD") + "/" + Date.now() + ".webp"
		})
	}

	//是否推荐方法
	const selectChange = (e) => {
		formData.value.select = e.detail.value;
	}

	//是否启用方法
	const enableChange = (e) => {
		formData.value.enable = e.detail.value;
	}

	//与父组件暴露的方法
	const open = () => {
		nextTick(() => {
			if (props.type == "add") formData.value.sort = props.maxSort;
		})
		classfiyPopup.value.open();
	}

	//取消新增
	const close = () => {
		classfiyPopup.value.close();
		formDataInit();
	}

	const formDataInit = () => {
		formData.value = {
			name: "",
			sort: 0,
			picurl: "",
			select: false,
			enable: false,
			tmpurl: ""
		}
	}

	defineExpose({
		open,
		close
	})
</script>

<style lang="scss" scoped>
	.classfiyPopup {
		background: #fff;
		width: 600px;
		min-height: 200px;
		padding: 50px 50px 50px 0;
	}
</style>